local Widget = require "widgets/widget"  -- 基础Widget类
local ImageButton = require "widgets/imagebutton"  -- ImageButton基类
local math = require "math"  -- 数学库

local ScrollList_ds = Class(Widget, function(self,items_data,params)
    -- print("ScrollList_ds 构造函数开始执行")
    -- print("参数信息：")
    -- print("rows:", rows)
    -- print("cols:", cols)
    -- print("items_data:", items_data and #items_data or "nil")
    -- print("grid_option:", grid_option and string.format("wide=%s, high=%s", grid_option.wide, grid_option.high) or "nil")
    
    Widget._ctor(self, "ScrollList_ds")
    -- print("参数信息：")
    self.grid_w = params.grid_option.wide or 70
    self.grid_h = params.grid_option.high or 70
    self.rows = params.rows
    self.cols = params.cols
    
    -- print("网格信息：")
    -- print("grid_w:", self.grid_w)
    -- print("grid_h:", self.grid_h)
    -- print("总网格数:", self.rows * self.cols)
    
    self.click_stepsize = params.click_stepsize -- 点击步长，表示每次点击移动多少行
    self.scroll_stepsize = params.scroll_stepsize -- 滚动步长，表示每次滚动移动多少行
    self.current_data_index = 1 -- 表示从第几个数据开始显示

    self.up_arrowbtn_option = {
        atlas = (params.up_arrowbtn_data and params.up_arrowbtn_data.atlas) or "images/my_futuristic_ui/my_futuristic_ui.xml",
        tex = (params.up_arrowbtn_data and params.up_arrowbtn_data.tex) or "white_scrollbar_arrow_up.tex",
        scale = (params.up_arrowbtn_data and params.up_arrowbtn_data.scale) or {1,1},
        offset = (params.up_arrowbtn_data and params.up_arrowbtn_data.offset) or {self.grid_w * self.cols / 2 + 35, 80},
    -- 默认位置在右上角
    }
    self.down_arrowbtn_option = {
        atlas = (params.down_arrowbtn_data and params.down_arrowbtn_data.atlas) or "images/my_futuristic_ui/my_futuristic_ui.xml",
        tex = (params.down_arrowbtn_data and params.down_arrowbtn_data.tex) or "white_scrollbar_arrow_down.tex",
        scale = (params.down_arrowbtn_data and params.down_arrowbtn_data.scale) or {1,1},
        offset = (params.down_arrowbtn_data and params.down_arrowbtn_data.offset) or {self.grid_w * self.cols / 2 + 35, -80},
    -- 默认位置在右下角
    }
    self.items_data_processed = {} -- 处理后的物品数据列表
    self.items_data_processfn = params.items_data_processfn -- 物品数据处理函数
    self.grid_processfn = params.grid_processfn -- 网格处理函数，用于根据items_data_processfn处理后的数据列表self.items_data生成相应的widget
    
    self.grid_list = {} -- 记录生成的网格列表

    self.grid_pos = {} -- 网格位置列表
    -- print("开始计算网格位置")
    for i = 1, self.rows do
        for j = 1, self.cols do
            local x = (2*j-self.cols-1)*self.grid_w/2
            local y = -(2*i-self.rows-1)*self.grid_h/2
            table.insert(self.grid_pos, {x, y})
            --print(string.format("网格位置 [%d,%d]: x=%d, y=%d", i, j, x, y))
        end
    end
    
    -- print("生成翻页箭头按钮")
    --#region 翻页箭头按钮
    self.up_arrowbtn = ImageButton(self.up_arrowbtn_option.atlas, self.up_arrowbtn_option.tex)
    self.up_arrowbtn:SetScale(self.up_arrowbtn_option.scale[1], self.up_arrowbtn_option.scale[2])
    self:AddChild(self.up_arrowbtn)
    self.up_arrowbtn:SetPosition(self.up_arrowbtn_option.offset[1], self.up_arrowbtn_option.offset[2])
    self.up_arrowbtn:SetOnClick(function()
        -- print("点击上箭头")
        self.current_data_index = self.current_data_index - self.scroll_stepsize * self.cols
        self.current_data_index = self:CheckIndex(self.current_data_index)
        self:UpdateGridByIndex(self.current_data_index) -- 更新网格显示
    end)

    self.down_arrowbtn = ImageButton(self.down_arrowbtn_option.atlas, self.down_arrowbtn_option.tex)
    self.down_arrowbtn:SetScale(self.down_arrowbtn_option.scale[1], self.down_arrowbtn_option.scale[2])
    self:AddChild(self.down_arrowbtn)
    self.down_arrowbtn:SetPosition(self.down_arrowbtn_option.offset[1], self.down_arrowbtn_option.offset[2])
    self.down_arrowbtn:SetOnClick(function()
        -- print("点击下箭头")
        self.current_data_index = self.current_data_index + self.scroll_stepsize * self.cols
        self.current_data_index = self:CheckIndex(self.current_data_index)
        self:UpdateGridByIndex(self.current_data_index) -- 更新网格显示
    end)
    --#endregion

    --print("开始创建网格")
    --#region 创建网格
    self:UpdateGridByItemsData(items_data) -- 更新网格显示
    --#endregion

    --print("ScrollList_ds 构造函数执行完成")
end)

-- 确保第一个显示的数据的index正确
function ScrollList_ds:CheckIndex(index)
    local min_index = 1
    local max_index = 1
    local temp = #self.items_data_processed % self.cols
    if temp == 0 then
        max_index = #self.items_data_processed - (self.rows * self.cols) + 1
        if max_index < 1 then
            max_index = 1
        end
    else
        max_index = #self.items_data_processed - temp - (self.rows - 1) * self.cols + 1
        if max_index < 1 then
            max_index = 1
        end
    end
    local index = math.clamp(index, min_index, max_index)
    return index, max_index
end

-- 内部物品数据不变的情况下,根据索引更新网格显示
function ScrollList_ds:UpdateGridByIndex(index)
    self:ClearAllGridWidgets() -- 清空所有网格widget
    --print("更新网格显示，当前索引:", index)
    for i = index, #self.items_data_processed, 1 do
        if i > index + self.rows * self.cols - 1 then
            --print("超出网格数量限制，停止更新")
            break
        end
        local grid = self.grid_processfn(self.items_data_processed[i])
        if grid ~= nil then
            self:AddChild(grid)
            grid:SetPosition(self.grid_pos[i - index + 1][1], self.grid_pos[i - index + 1][2])
            table.insert(self.grid_list, grid)
        end
    end

    if index ~= 1 and #self.items_data_processed ~= 0 then
        self.up_arrowbtn:Show() -- 显示上箭头按钮
    else
        self.up_arrowbtn:Hide() -- 隐藏上箭头按钮
    end


    local _,max_index = self:CheckIndex(index)
    if index < max_index and #self.items_data_processed ~= 0 then
        self.down_arrowbtn:Show() -- 显示下箭头按钮
    else
        self.down_arrowbtn:Hide() -- 隐藏下箭头按钮
    end
end

-- 更新网格显示，物品数据发生变化
function ScrollList_ds:UpdateGridByItemsData(items_data)
    --print("更新网格显示，物品数据发生变化")
    self:ClearAllGridWidgets() -- 清空所有网格widget
    self.items_data_processed = {} -- 清空物品数据列表
    -- for index, item_data in ipairs(items_data) do
    --     local list = self.items_data_processfn(item_data)
    --     if list ~= nil then
    --         table.insert(self.items_data_processed, list)
    --     end
    -- end
    self.items_data_processed = self.items_data_processfn(items_data) or {}
    self.current_data_index = 1 -- 重置当前索引为1
    self:UpdateGridByIndex(self.current_data_index) -- 更新网格显示
    
end

--清空所有网格widget
function ScrollList_ds:ClearAllGridWidgets()
    for key, value in pairs(self.grid_list) do
        value:Kill() -- 销毁网格widget
    end
    self.grid_list = {} -- 清空网格列表
end

--设置滚轮滚动事件
function ScrollList_ds:OnControl(control, down)
    if self._base.OnControl(self, control, down) then return true end
	
	-- if not down and control == CONTROL_CANCEL then 
	-- 	self:Cancel()
	-- 	return true
	-- end

	if down then
		if control == CONTROL_SCROLLBACK then
			self.current_data_index = self.current_data_index - self.scroll_stepsize * self.cols
        elseif control == CONTROL_SCROLLFWD then
			self.current_data_index = self.current_data_index + self.scroll_stepsize * self.cols
		end
        self.current_data_index = self:CheckIndex(self.current_data_index)
        self:UpdateGridByIndex(self.current_data_index)
        return true
	end
end

return ScrollList_ds